/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.com;

//import static acceso.servlet.Transa_Engine2.HSESSION;
import pe.com.unidades.Multas;
import pe.com.unidades.Papeletas;
import pe.com.unidades.Placa;
import pe.com.unidades.Telefono;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.LinkedBlockingQueue;
import pe.com.unidades.Chip;
import pe.com.unidades.Vehiculo;

/**
 *
 * @author romulogalindo
 * @see Clase que procesa el resultado de las operaciones basicas
 */
public class ColaProcesamiento extends Thread {

    private static LinkedBlockingQueue<Object> tasks = null;
    private boolean alive = true;
    private static boolean inprocess = false;

    Connection con1;
    Statement st;
    String driver1 = "";
    String server1 = "";
    String port1 = "";
    String database1 = "";
    String user1 = "";
    String password1 = "";
    String proceso = "P";
    String tipo = "";
    String limit = "";
    String[] arg;

    int numI = 0;
    int m_id = 1;

    static {
        tasks = new LinkedBlockingQueue<>();
        System.out.println("[Jaguar: ColaProcesamiento] Connectado a la DB");
    }

    public ColaProcesamiento() {
        System.out.println("COla de procesamiento");
        con1 = DO();
        try {
            st = con1.createStatement();
        } catch (SQLException ep) {
            System.out.println("Errorr:\n[Class] " + ep.getClass() + "\n" + ep.getMessage());
            return;
        }
        System.out.println("Conectado");
        setPriority(9);
    }

    public ColaProcesamiento(String[] args) {
        arg = args;
        con1 = DO(arg);
        try {
            st = con1.createStatement();
        } catch (SQLException ep) {
            System.out.println("Errorr:\n[Class] " + ep.getClass() + "\n" + ep.getMessage());
            return;
        }
        setPriority(9);
    }

    public static void nuevoProceso(Object task) {
        tasks.add(task);
    }

    public void stopme() {
        this.alive = false;
        tasks.add(new String("Fin"));
    }

    @Override
    public void run() {
        while (alive) {
            String sql = "";
            Object task = null;
            try {
                inprocess = true;
                task = tasks.take();
                if (task instanceof Telefono) {
                    Telefono t = (Telefono) task;
                    sql = "/*[" + m_id + "]*/select * from wftelefo.pbactualizar_telefono(\'" + t.getNumero() + "\', \'" + t.getOperador() + "\', \'" + t.getNumeroRPM() + "\');";
                    m_id = m_id + 1;
                    ResultSet rpta = st.executeQuery(sql);
                    System.out.println(sql);
                } else if (task instanceof Placa) {
                    Placa p = (Placa) task;
                    if (p.getLs_papeletas() != null & p.getLs_papeletas().size() > 0) {
                        for (Papeletas papeleta : p.getLs_papeletas()) {
                            sql = "select * from vehmay.pbpapele_insupd('" + p.getCo_plaveh() + "', '" + papeleta.getConcepto() + "', '" + papeleta.getCodigopago() + "', '" + papeleta.getFecinf_fecemi() + "', " + papeleta.getImporte() + ", " + papeleta.getGast_cost() + ", " + papeleta.getDescuento() + ", '" + papeleta.getEstado() + "', '" + papeleta.getFalta() + "', '" + papeleta.getLicencia() + "')";
                            ResultSet rpta = st.executeQuery(sql);
                            System.out.println(sql);
                        }
                    }
                    if (p.getLs_multas() != null & p.getLs_multas().size() > 0) {
                        for (Multas multa : p.getLs_multas()) {
                            sql = "select * from vehmay.pbimpveh_insupd('" + p.getCo_plaveh() + "', " + multa.getAnhio() + "::smallint, " + multa.getCuota() + "::smallint, '" + multa.getCodigo_pago() + "', " + multa.getDeuda_total() + ", " + multa.getPagado() + ", " + (multa.getVencimiento() != null ? " '" + ((multa.getVencimiento().length() > 5) ? multa.getVencimiento() : null) + "' " : null) + ", '" + multa.getEstado() + "', '" + multa.getEstado_documento_deuda() + "', '" + multa.getEstado_documento_notificado() + "', " + (multa.getFecha_notificacion() != null ? "'" + ((multa.getFecha_notificacion().length() > 5) ? multa.getFecha_notificacion() : null) + "'" : null) + ", '" + multa.getEstado_expedi() + "', '" + multa.getReferencia() + "');";
                            ResultSet rpta = st.executeQuery(sql);
                            System.out.println(sql);
                        }
                    }
                    System.out.println("::[" + p.getTHREAD_ID() + "-" + p.getSUBTHREAD_ID() + "]::" + p.getCo_plaveh() + "::\n");
                } else if (task instanceof Chip) {
                    Chip c = (Chip) task;
                    sql = "/*[" + m_id + "]*/select * from arllamad.insert_saldo_minuto(\'" + c.getNu_chip() + "\', " + c.getCa_minasi() + ", " + c.getCa_mincon() + ");";
                    m_id = m_id + 1;
                    ResultSet rpta = st.executeQuery(sql);
                    System.out.println(sql);
                }else if (task instanceof Vehiculo) {
                    Vehiculo v = (Vehiculo) task;
                    sql = "/*[" + m_id + "]*/select * from wfvehicu.sunarp_actualizar('"+v.getCo_plaveh()+"', '"+v.getNu_serveh()+"', '"+v.getNu_ideveh()+"', '"+v.getNu_motveh()+"', '"+v.getNo_colveh()+"', '"+v.getNo_marveh()+"', '"+v.getNo_modveh()+"', \'"+v.getNo_proveh()+"\', '"+v.getNo_sedveh()+"');";
                    m_id = m_id + 1;
                    ResultSet rpta = st.executeQuery(sql);
                    System.out.println(sql);
                }
                inprocess = false;
            } catch (InterruptedException e) {
                inprocess = false;
                System.out.println("Hilo[" + alive + "] interrumpido y a dormir");
            } catch (SQLException ex) {
                inprocess = false;
                //destruir objeto CON-SQL
                System.out.println("Error SQL:" + ex.getSQLState() + "::" + ex.getMessage() + "\nsql:" + sql);
                if (numI < 3) {
                    try {
                        con1.close();
                        con1 = null;
                    } catch (SQLException ep) {
                        try {
                            con1 = null;
                        } catch (Exception ep2) {
                        }
                    }
                    //reconectar a la DB
                    con1 = DO(arg);
                    //reasignar la tarea
                    tasks.add(task);
                    numI = numI + 1;
                }
            }
        }
    }

    public static boolean isEmpty() {
        return tasks.isEmpty();
    }

    public static int taskssize() {
        return tasks.size();
    }

    public static synchronized boolean proceso() {
        return inprocess;
    }

    public Connection DO(String[] args) {
        for (String arg : args) {
            String keyName = arg.split("=")[0];
            switch (keyName) {
                case "-driver1": {
                    driver1 = arg.split("=")[1];
                    break;
                }
                case "-server1": {
                    server1 = arg.split("=")[1];
                    break;
                }
                case "-port1": {
                    port1 = arg.split("=")[1];
                    break;
                }
                case "-database1": {
                    database1 = arg.split("=")[1];
                    break;
                }
                case "-user1": {
                    user1 = arg.split("=")[1];
                    break;
                }
                case "-password1": {
                    password1 = arg.split("=")[1];
                    break;
                }
                case "-proceso": {
                    proceso = arg.split("=")[1];
                    break;
                }
                case "-tipo": {
                    tipo = arg.split("=")[1];
                    break;
                }
                case "-limit": {
                    limit = arg.split("=")[1];
                    break;
                }
            }
        }
//        System.out.println("Extrayendo data...");
        try {
            if (driver1.contentEquals("")) {
                driver1 = "org.postgresql.Driver";
                System.out.println("Cargando driver por default....:" + driver1);
            }
            Class.forName(driver1);
//            System.out.println("Cargando driver\t[OK]");
        } catch (ClassNotFoundException ep) {
            System.out.println("Error-cargando driver:\n[Class] " + ep.getClass() + "\n" + ep.getMessage());
            return null;
        }
        try {
            con1 = DriverManager.getConnection("jdbc:postgresql://" + server1 + ":" + port1 + "/" + database1, "" + user1 + "", "" + password1 + "");
            return con1;
        } catch (SQLException ep) {
            System.out.println("Error:\n[Class] " + ep.getClass() + "\n" + ep.getMessage());
            return null;
        }
    }

    public Connection DO() {
        try {
            Class.forName("org.postgresql.Driver");
            System.out.println("Cargando driver\t[OK]");
//            con1 = DriverManager.getConnection("jdbc:postgresql://wf1.accesocrediticio.com:5432/WFACR", "rgalindo", "$acceso123456$");
            con1 = DriverManager.getConnection("jdbc:postgresql://wf1.accesocrediticio.com:5432/WFACR", "mdiaz", "acceso123456");
//            st = con1.createStatement();
            return con1;
        } catch (ClassNotFoundException | SQLException ep) {
            System.out.println("Errorr:\n[Class] " + ep.getClass() + "\n" + ep.getMessage());
            return null;
        }
    }

}
